/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pacificlms.MainPanel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import pacificlms.DataHolder;
import pacificlms.MasterConnection;
import pacificlms.Verifiable.*;
import pacificlms.Verifiable.Database.*;
import pacificlms.Error.ErrorHandle;
import java.lang.reflect.Method;
import java.util.Calendar;
import javax.swing.DefaultListModel;
import pacificlms.LoggedMember;
import sun.reflect.generics.tree.Tree;

/**
 * InformationCopy is responsible for displaying, editing, and creating
 * Copies (the InformationResource panel does not create copies)
 * @author Brian Hume
 */
public class InformationCopy extends CentralUIPanel {

    /**
     * Creates a InformationCopy Panel with a specified resource name
     */
    public InformationCopy(String ResourceCode) {//fixme make this take a copy so that we can have a good ResourceCode and number
        super(null);
        initComponents();
        
        Create((Copy)null);
        if (ResourceCode != null)
            txtResourceCode.setText(ResourceCode);
    }

    /**
     * Displays a specified Copy
     */
    public InformationCopy(VerifiableObject VO) {
        super(null);
        initComponents();
        
        Create((Copy)VO);
    }

    protected Method SetMethodRef;
    protected Method SetResourceMethodRef;
    Copy CurrentCopy = null;
    boolean NewCopy = true;
    
    /**
     * Creates the CopyInformation Panel, if null copy create a new one, fill the fields, and find the linked methods
     * @param Copy The copy to display
     */
    void Create(Copy Copy)
    {
        CurrentCopy = Copy;
        if (Copy == null)
            NewCopy = true;
        else
            NewCopy = false;
        FillFields();
        
        try
        {
            Method[] MethodList = this.getClass().getDeclaredMethods();
            
            for(Method ML: MethodList)
            {
                if (ML.getName().equals("SetCopy"))
                    SetMethodRef = ML;
                if (ML.getName().equals("SetResource"))
                    SetResourceMethodRef = ML;
                System.out.println(ML.getName());
            }
            //Class[] Arglist = new Class[1];
            //Arglist[0] = VerifiableObject.class;
            //SetMethodRef = ReflectionHelper.getMethod this.getClass().getMethod("SetMethod", Arglist);
        }
        catch(Exception Ex)
        {
            System.out.println(Ex.toString());
            SetMethodRef = null;
        }
    }
//fixme ,ultiple logins    
    /**
     * Fills all of the fields on the form, list the checkouts that this copy has participated in, sets the locked features based on user
     */
    void FillFields()
    {
        if (CurrentCopy == null)
        {
            CurrentCopy = new Copy();
        }
        
        txtResourceCode.setText(CurrentCopy.ResourceCode(null));
        txtCopyNumber.setText(CurrentCopy.CopyNumber(null));
        txtCallNumber.setText(CurrentCopy.CallNumber(null));
                
        SetCopyStatus(CurrentCopy.CopyStatus(null));
        ListCheckouts();
        

        if (LoggedMember.getInstance().IsLibrarian())
        {
            btnNew.setEnabled(true);
            btnSearch.setEnabled(true);
            btnSave.setEnabled(true);
            btnFindResource.setEnabled(true);
        }
        else
        {
            btnNew.setEnabled(false);
            btnSearch.setEnabled(false);
            btnSave.setEnabled(false);
            btnFindResource.setEnabled(false);
        }
    }
    
    /**
     * Sets the value in the combo to match a string
     * @param Status the string to be matched
     */
    public void SetCopyStatus(String Status)
    {
        if (Status == null)
        {
            Status = (String)cboCopyStatus.getItemAt(1);//get student
        }
        int Max = cboCopyStatus.getItemCount();
        for (int itr = 0; itr < Max; itr++)
        {
            if (((String)cboCopyStatus.getItemAt(itr)).equalsIgnoreCase(Status))
            {
                cboCopyStatus.setSelectedIndex(itr);
                return;
            }
        }
    }
    
    /**
     * Find all checkouts that refer to this copy
     */
    void ListCheckouts()
    {
        String CallNumber = CurrentCopy.CallNumber(null);
        lstCheckOuts.setModel(new DefaultListModel());
        if (CallNumber != null || CallNumber == "")
        {
            ArrayList<VerifiableObject> CheckOutList = CurrentCopy.GetRelatedData(CheckOut.class, 1000);
            DefaultListModel DLM = new DefaultListModel();
            if (CheckOutList == null)
                return;
            for(VerifiableObject VO: CheckOutList)
            {
                DLM.addElement(VO);
            }
            lstCheckOuts.setModel(DLM);
            return;
        }
    }
    
    public String TabName()
    {
        return "Copy Catalog";
    }
    /**
     * Recreates the copy from the fields
     * @return if the member was validated
     */
    boolean RegenerateMember()
    {
        Copy Copy = new Copy();
        
        Copy.ResourceCode(txtResourceCode.getText());
        Copy.CopyNumber(txtCopyNumber.getText());
        Copy.CallNumber(txtCallNumber.getText());
        Copy.CopyStatus(cboCopyStatus.getSelectedItem().toString());
        
        ListCheckouts();
        
        boolean Created = Copy.Verify();
        if(Created)
        {
            CurrentCopy = Copy;
        }
        return Created;
    }
    
    /**
     * Creates a new copy
     */
    void NewCopy()
    {
        NewCopy = true;
        CurrentCopy = null;
        FillFields();
    }
    
    /**
     * Saves the current copy
     */
    void Save()
    {
        if (RegenerateMember())
        {
            try
            {
                Connection con = MasterConnection.getInstance();
                Statement stmt = con.createStatement();
                String SQL = "";
                if (NewCopy)
                    SQL = CurrentCopy.InsertRecrodSQL();
                else
                    SQL = CurrentCopy.UpdateRecrodSQL();
                stmt.executeUpdate(SQL);
                
                String Str = "Save successfull.";
                
                if (NewCopy)
                    Str = "The copy has been successfully added to the database.";
                    
                JOptionPane.showMessageDialog(null, Str, "Success", JOptionPane.INFORMATION_MESSAGE);
            }
            catch(Exception Ex)
            {
                JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    /**
     * Sets the current copy to a copy from the search form (does not change copy if null
     * @param VO the new copy to set to
     */
    public void SetCopy(VerifiableObject VO)
    {
        if (VO == null)
            return;
        
        CurrentCopy = (Copy)VO;
        NewCopy = false;
        FillFields();
    }
    /**
     * Sets the resource code to new code
     * @param VO new resource to use
     */
    public void SetResource(VerifiableObject VO)
    {
        if (VO == null)
            return;
        
        txtResourceCode.setText(((Resource)VO).ResourceCode(null));
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel11 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtResourceCode = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtCopyNumber = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtCallNumber = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        btnFindResource = new javax.swing.JButton();
        txtILL = new javax.swing.JTextField();
        btnFindILL = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        cboCopyStatus = new javax.swing.JComboBox();
        btnNew = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnSearch = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstCheckOuts = new javax.swing.JList();

        setPreferredSize(new java.awt.Dimension(615, 535));

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 22));
        jLabel11.setText("Copy Information");

        jLabel1.setText("Resource Code");

        jLabel2.setText("Copy #");

        jLabel5.setText("Checkout History");

        jLabel6.setText("Call #");

        btnFindResource.setText("Search");
        btnFindResource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFindResourcejButton7ActionPerformed(evt);
            }
        });

        txtILL.setEnabled(false);

        btnFindILL.setText("Search");
        btnFindILL.setEnabled(false);

        jLabel8.setText("Copy Status");

        cboCopyStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "available", "damaged", "lost", "retired" }));

        btnNew.setText("New Copy");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        jLabel9.setText("Inter Library Loan");
        jLabel9.setOpaque(true);

        jScrollPane1.setViewportView(lstCheckOuts);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCallNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtCopyNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtResourceCode, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnFindResource, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 225, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnNew, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 175, Short.MAX_VALUE)
                        .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cboCopyStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtILL, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFindILL, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel11)
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtResourceCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFindResource, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCopyNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCallNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtILL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFindILL, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(cboCopyStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(44, 44, 44)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnSearch)
                        .addComponent(btnNew))
                    .addComponent(btnSave)
                    .addComponent(btnClose))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Searches for a new resource code
     */
    private void btnFindResourcejButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindResourcejButton7ActionPerformed
        MainPanel.GetMainPanel().AddCentralUIPanel(new SearchForResource(true), this, SetResourceMethodRef);
    }//GEN-LAST:event_btnFindResourcejButton7ActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        NewCopy();
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        Close();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        Save();
    }//GEN-LAST:event_btnSaveActionPerformed

    /**
     * Search for a new copy
     */
    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        MainPanel.GetMainPanel().AddCentralUIPanel(new SearchForCopy(true), this, SetMethodRef);
    }//GEN-LAST:event_btnSearchActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnFindILL;
    private javax.swing.JButton btnFindResource;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox cboCopyStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstCheckOuts;
    private javax.swing.JTextField txtCallNumber;
    private javax.swing.JTextField txtCopyNumber;
    private javax.swing.JTextField txtILL;
    private javax.swing.JTextField txtResourceCode;
    // End of variables declaration//GEN-END:variables
}
